//
//  MediaShareBB.m
//  MediaShareBB
//
//  Created by Artak Gevorgyan on 5/23/13.
//  Copyright (c) 2013 InnoriseEntertainment. All rights reserved.
//

#import "AppDelegate.h"
#import "MediaShareBB.h"
#import "MediaShareCommunity.h"
#import "MediaShareBBUtilityMethods.h"
#import "MediaShareData.h"
#import "FBMediaShareCommunity.h"
#import "TwitterMediaShareCommunity.h"
#import "InstagramMediaShareCommunity.h"
#import "GooglePlusMediaShareCommunity.h"
#import "DropboxMediaShareCommunity.h"
#import "SkyDriveMediaShareCommunity.h"
#import "GoogleDriveMediaShareCommunity.h"
#import "YouTubeMediaShareCommunity.h"
#import "SaveToPhotosMediaShareCommunity.h"
#import "EmailMediaShareCommunity.h"

#import "MediaShareCommunityEntity.h"
#import "FBMediaShareCommunityEntity.h"

#import "ALAssetsLibrary+CustomPhotoAlbum.h"
#import <MessageUI/MessageUI.h>

@interface MediaShareBB ()<MediaShareCommunityDelegate,
							UITableViewDataSource,
							UITableViewDelegate,
							UIDocumentInteractionControllerDelegate,
							MFMailComposeViewControllerDelegate>
{
	NSMutableArray* _configuredCommunities;
	MediaShareCommunity* _selectedCommunity;
	UINavigationBar* _navBar;
	UIDocumentInteractionController* _documentInteractionController;
}

@end

@implementation MediaShareBB

-(id) init {
	self = [super init];
	if (self) {
		[self setFrameToView];
		_configuredCommunities = [[NSMutableArray alloc] init];
	}
	return self;
}

#pragma mark - Public methods

-(id) initWithAllCommunitiesSupport {
	self = [super init];
	if (self) {
		[self setFrameToView];
		_configuredCommunities = [[NSMutableArray alloc] init];
		[self initSupportedCommunitiesArray];
	}
	return self;
}

-(void) addSharingNetwork:(enum MediaShareCommunities) sh
		  withCredentials:(NSDictionary*) credentials {
	MediaShareCommunity* cmm = [self createCommunityBasedOnType:sh];
	[cmm configureWithCredentials:credentials];
	cmm.delegate = self;
	[_configuredCommunities addObject:cmm];
}

-(NSArray*) configuredCommunities {
	return _configuredCommunities;
}

-(void) communitySelected:(MediaShareCommunity*) comm {

}

-(void) setSelectedCommunityWithType:(enum MediaShareCommunities) commType {
	_selectedCommunity = [self getCommunityByType:commType];
}

-(MediaShareCommunity*) getSelectedCommunity  {
    return _selectedCommunity;
}

-(void) sendViaEmail:(MediaShareData*) data {
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController* mailer = [[MFMailComposeViewController alloc] init];
        NSString* str = [data.fileName stringByAppendingString:@".mp4"];
        mailer.mailComposeDelegate = self;
        if (data.mediaType == IMAGE_MEDIA_TYPE) {
            [mailer addAttachmentData:data.data
                             mimeType:@"image/png"
                             fileName:@"image"];
        } else if (data.mediaType == VIDEO_MEDIA_TYPE) {
            [mailer addAttachmentData:data.data
                             mimeType:@"video/mp4"
                             fileName:str];
        } else if (data.mediaType == URL_MEDIA_TYPE) {
            [mailer setMessageBody:data.fileName isHTML:NO];
        }
        
        // only for iPad
        // mailer.modalPresentationStyle = UIModalPresentationPageSheet;
		AppDelegate* app = [UIApplication sharedApplication].delegate;
		UIViewController* controller = app.window.rootViewController;
		[controller presentViewController:mailer animated:YES
						 completion:nil];
    } else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
    }
}

#pragma mark - UITabelViewDataSource methods

-(NSInteger) tableView:(UITableView*) tableView numberOfRowsInSection:(NSInteger) section {
	return _selectedCommunity.entities.count;
}

-(UITableViewCell*) tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath {
	static NSString* cellIdentifier = @"Cell";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
									   reuseIdentifier:cellIdentifier];
	}
	MediaShareCommunityEntity* entity = [_selectedCommunity.entities objectAtIndex:indexPath.row];
	NSString* s = entity.entityId;
	if ([entity isKindOfClass:[FBMediaShareCommunityEntity class]]) {
		NSString* f = ((FBMediaShareCommunityEntity*) entity).firstName;
		NSString* l = ((FBMediaShareCommunityEntity*) entity).lastName;
		s = [NSString stringWithFormat:@"%@ %@", f, l];
	}
	s = entity.isMyEntity ? @"Me" : s;
	cell.textLabel.text = s;
	cell.textLabel.textColor = entity.isMyEntity ? [UIColor blueColor] : [UIColor blackColor];
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	return cell;
}

#pragma mark - UITabelViewDelegate methods

-(void) tableView:(UITableView*) tableView didSelectRowAtIndexPath:(NSIndexPath*) indexPath {
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];

	MediaShareCommunityEntity* entity = [_selectedCommunity.entities
										 objectAtIndex:indexPath.row];;
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
		[_selectedCommunity.selectedEntities removeObject:entity];
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else {
		[_selectedCommunity.selectedEntities addObject:entity];
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}

#pragma mark - MediaShareCommunityDelegate methods

-(UIViewController*) targetViewController {
    return self;
}

-(void) loginCanceled {
	NSLog(@"%s login canceled", __PRETTY_FUNCTION__);
	[_delegate canceled];
}

-(void) loginSuccess {
	NSLog(@"%s Success login", __PRETTY_FUNCTION__);
	if ([MediaShareBBUtilityMethods isObject:_delegate
						  respondsToSelector:@selector(mediaShareCommunitySelected:)]) {
		[_delegate mediaShareCommunitySelected:_selectedCommunity];
	}
//	if ([_selectedCommunity isKindOfClass:[FBMediaShareCommunity class]]) {
//		[(FBMediaShareCommunity*) _selectedCommunity fetchFriends];
////		[_selectedCommunity showFriendsPickerOnView:self];
//	}
}

-(void) loginFailedWithError:(NSError*) error {
	NSLog(@"Login failed with error:%@", error);
	[_delegate canceled];
}

-(void) entitiesFetchedForCommunity:(MediaShareCommunity*) comm {
	[self addNavigationBarForCommunity:comm];
	[self addEntriesTableViewForCommunity:comm];
}

-(void) entitiesSelectedForCommunity:(MediaShareCommunity*) comm {
	if ([MediaShareBBUtilityMethods isObject:_delegate
						  respondsToSelector:@selector(mediaShareCommunitySelected:)]) {
		[_delegate mediaShareCommunitySelected:comm];
	}
}

-(void) communityViewWillClose {
//	[self.view removeFromSuperview];
	if ([MediaShareBBUtilityMethods isObject:_delegate
						  respondsToSelector:@selector(canceled)]) {
		[_delegate canceled];
	}
}

-(void) willSharingMedia:(MediaShareData*) data through:(MediaShareCommunity*) comm {
	if (comm.communityType == MEDIA_SHARE_COMMUNITY_INSTAGRAM) {
		[self shareUsingInstagramApp:data];
	} else if (comm.communityType == MEDIA_SHARE_COMMUNITY_EMAIL) {
		[self sendViaEmail:data];
	} else {
		if ([MediaShareBBUtilityMethods isObject:_delegate
							  respondsToSelector:@selector(willShareMedia:through:)]) {
			[_delegate willShareMedia:data through:comm];
		}
	}
}

-(void) didFinishSharingMedia:(MediaShareData*) data through:(MediaShareCommunity*) comm {
	if ([MediaShareBBUtilityMethods isObject:_delegate
						  respondsToSelector:@selector(didFinishSharingMedia:through:)]) {
		[_delegate didFinishSharingMedia:data through:comm];
	}
}

-(void) didFailedSharingMedia:(MediaShareData*) data through:(MediaShareCommunity*) comm
					withError:(NSError*) error {
	if ([MediaShareBBUtilityMethods isObject:_delegate
						  respondsToSelector:@selector(didFailedSharingMedia:through:withError:)]) {
		[_delegate didFailedSharingMedia:data through:comm withError:error];
	}
}

#pragma mark - MFMailComposeViewControllerDelegate methods

-(void) mailComposeController:(MFMailComposeViewController*) controller
		  didFinishWithResult:(MFMailComposeResult) result error:(NSError*) error
{
	switch (result)
	{
		case MFMailComposeResultCancelled:
			NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued");
			break;
		case MFMailComposeResultSaved:
			NSLog(@"Mail saved: you saved the email message in the Drafts folder");
			break;
		case MFMailComposeResultSent:
			NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send the next time the user connects to email");
			break;
		case MFMailComposeResultFailed:
			NSLog(@"Mail failed: the email message was nog saved or queued, possibly due to an error");
			break;
		default:
			NSLog(@"Mail not sent");
			break;
	}
	[_delegate canceled];
	AppDelegate* app = [UIApplication sharedApplication].delegate;
	UIViewController* cont = app.window.rootViewController;
	[cont dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - Private methods

-(void) initSupportedCommunitiesArray {
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_FACEBOOK withCredentials:nil];

	NSDictionary* twitterCredentials = [[NSDictionary alloc] initWithObjectsAndKeys:
										   MEDIA_SHARE_BB_TWITTER_CONSUMER_KEY, @"consumerKey",
										   MEDIA_SHARE_BB_TWITTER_CONSUMER_SECRET, @"consumerSecret",
										   MEDIA_SHARE_BB_TWITTER_CALLBACK_URL, @"callbackUrl",
										   nil];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_TWITTER withCredentials:twitterCredentials];

	if ([MediaShareBBUtilityMethods isInstagramAppInstalled]) {
		[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_INSTAGRAM withCredentials:nil];
	}

	NSDictionary* googlePlusCredentials = [[NSDictionary alloc] initWithObjectsAndKeys:
										   MEDIA_SHARE_BB_GOOGLE_PLUS_CLIENT_ID, @"clientId",
										   nil];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_GOOGLE_PLUS
			withCredentials:googlePlusCredentials];

	NSDictionary* dropboxCredentials = [[NSDictionary alloc] initWithObjectsAndKeys:
											MEDIA_SHARE_BB_DROPBOX_APP_KEY, @"appKey",
											MEDIA_SHARE_BB_DROPBOX_SECRET_KEY, @"secretKey",
											nil];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_DROPBOX
			withCredentials:dropboxCredentials];

	NSDictionary* googleDriveCredentials = [[NSDictionary alloc] initWithObjectsAndKeys:
											MEDIA_SHARE_BB_GOOGLE_DRIVE_CLIENT_ID, @"clientId",
											MEDIA_SHARE_BB_GOOGLE_DRIVE_SECRET_ID, @"secretId",
											nil];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_GOOGLE_DRIVE
			withCredentials:googleDriveCredentials];

	NSDictionary* skydriveCredentials = [[NSDictionary alloc] initWithObjectsAndKeys:
											MEDIA_SHARE_BB_SKY_DRIVE_CLIENT_ID, @"clientId",
											nil];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_SKY_DRIVE
			withCredentials:skydriveCredentials];

	NSDictionary* saveToPhotosCredentials = [[NSDictionary alloc] initWithObjectsAndKeys:
											 MEDIA_SHARE_BB_SAVE_TO_PHOTOS_ALBUM_NAME, @"albumName",
											 nil];
	NSDictionary* youTubeCredentials = [[NSDictionary alloc] initWithObjectsAndKeys:
											 MEDIA_SHARE_BB_YOUTUBE_CLIENT_ID, @"clientId",
											 MEDIA_SHARE_BB_YOUTUBE_CLIENT_SECRET, @"clientSecret",
											 nil];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_YOUTUBE
			withCredentials:youTubeCredentials];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_SAVE_TO_PHOTOS
			withCredentials:saveToPhotosCredentials];
	[self addSharingNetwork:MEDIA_SHARE_COMMUNITY_EMAIL withCredentials:nil];
}

-(MediaShareCommunity*) getCommunityByType:(enum MediaShareCommunities) cmmType {
	for (MediaShareCommunity* cmm in _configuredCommunities) {
		if (cmm.communityType == cmmType) {
			return cmm;
		}
	}
	return nil;
}

-(void) setFrameToView {
	CGRect screenRect = [[UIScreen mainScreen] bounds];
	CGFloat horizontalOffset = 0;
	CGFloat verticalOffset = 0;
	if (IPHONE5 || IPHONE) {
		horizontalOffset = MEDIA_SHARE_BB_VIEW_HORIZONTAL_OFFSET_IPHONE;
		verticalOffset = MEDIA_SHARE_BB_VIEW_VERTICAL_OFFSET_IPHONE;
	} else if (IPAD) {
		horizontalOffset = MEDIA_SHARE_BB_VIEW_HORIZONTAL_OFFSET_IPAD;
		verticalOffset = MEDIA_SHARE_BB_VIEW_VERTICAL_OFFSET_IPAD;
	}
	CGFloat x = horizontalOffset;
	CGFloat y = verticalOffset;
	CGFloat w = 0;
	CGFloat h = 0;
	UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
	if (orientation == UIInterfaceOrientationLandscapeLeft
		|| orientation == UIInterfaceOrientationLandscapeRight) {
		w = screenRect.size.height - 2 * horizontalOffset;
		h = screenRect.size.width - 2 * verticalOffset;
	} else {
		w = screenRect.size.width - 2 * horizontalOffset;
		h = screenRect.size.height - 2 * verticalOffset;
	}
	self.view.frame = CGRectMake(x, y, w, h);
	self.view.backgroundColor = [UIColor clearColor];
}

-(MediaShareCommunity*) createCommunityBasedOnType:(enum MediaShareCommunities) communityType {
	MediaShareCommunity* cmm;
	switch (communityType) {
		case MEDIA_SHARE_COMMUNITY_FACEBOOK: {
			cmm = [[FBMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_TWITTER: {
			cmm = [[TwitterMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_INSTAGRAM: {
			cmm = [[InstagramMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_GOOGLE_PLUS: {
			cmm = [[GooglePlusMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_DROPBOX: {
			cmm = [[DropboxMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_GOOGLE_DRIVE: {
			cmm = [[GoogleDriveMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_SKY_DRIVE: {
			cmm = [[SkyDriveMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_YOUTUBE: {
			cmm = [[YouTubeMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_SAVE_TO_PHOTOS: {
			cmm = [[SaveToPhotosMediaShareCommunity alloc] init];
			break;
		} case MEDIA_SHARE_COMMUNITY_EMAIL: {
			cmm = [[EmailMediaShareCommunity alloc] init];
			break;
		} default:
			break;
	}
	return cmm;
}

-(void) addNavigationBarForCommunity:(MediaShareCommunity*) comm {
	CGRect r = CGRectMake(0, 0,
						  self.view.frame.size.width,
						  MEDIA_SHARE_BB_NAVIGATION_BAR_HEIGHT);
	UINavigationBar* navBar = [[UINavigationBar alloc] initWithFrame:r];
	UIBarButtonItem* rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
																	style:UIBarButtonItemStyleDone
																   target:self
																   action:@selector(doneButtonPressed)];
	UIBarButtonItem* leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel"
																	style:UIBarButtonItemStyleBordered
																   target:self
																   action:@selector(cancelButtonPressed)];
	UINavigationItem* item = [[UINavigationItem alloc] init];
	item.rightBarButtonItem = rightButton;
	item.leftBarButtonItem = leftButton;
	[navBar pushNavigationItem:item animated:YES];
	navBar.topItem.title = comm.name;
	[self.view addSubview:navBar];
}

-(void) addEntriesTableViewForCommunity:(MediaShareCommunity*) comm {
	CGRect f = CGRectMake(0, MEDIA_SHARE_BB_NAVIGATION_BAR_HEIGHT,
						  self.view.frame.size.width,
						  self.view.frame.size.height - MEDIA_SHARE_BB_NAVIGATION_BAR_HEIGHT);
	UITableView* t = [[UITableView alloc] initWithFrame:f];
	t.delegate = self;
	t.dataSource = self;
	[self.view addSubview:t];
}

-(void) communityButtonClicked:(id) sender {
	UIButton* b = (UIButton*) sender;
	MediaShareCommunity* cm = [_configuredCommunities objectAtIndex:b.tag];
	NSLog(@"Selected community:%@", cm.name);
}

-(void) cancelButtonPressed {
	[self.view removeFromSuperview];
	if ([MediaShareBBUtilityMethods isObject:_delegate
						  respondsToSelector:@selector(canceled)]) {
		[_delegate canceled];
	}
}

-(void) doneButtonPressed {
	NSLog(@"selected entities:%@", _selectedCommunity.selectedEntities);
	UIImage* image = [UIImage imageNamed:@"example.png"];
	NSString* name = [NSString stringWithFormat:@"upload_%@",
					  [MediaShareBBUtilityMethods getCurrentData]];
	MediaShareData* data = [[MediaShareData alloc] initWithImage:image andName:name];
	[_selectedCommunity shareMedia:data];
}

-(void) shareUsingInstagramApp:(MediaShareData*) data {
    if ([MediaShareBBUtilityMethods isInstagramAppInstalled]) {
        NSString* documentDirectory = [NSHomeDirectory()
									   stringByAppendingPathComponent:@"Documents"];
        NSString* saveImagePath = [documentDirectory
										stringByAppendingPathComponent:@"Image.igo"];
        [data.data writeToFile:saveImagePath atomically:YES];

        NSURL* imageURL = [NSURL fileURLWithPath:saveImagePath];

		_documentInteractionController = [[UIDocumentInteractionController alloc] init];
        _documentInteractionController.delegate = self;
        _documentInteractionController.UTI = @"com.instagram.photo";
        _documentInteractionController.annotation = [NSDictionary dictionaryWithObjectsAndKeys:
													 @"Caption", @"InstagramCaption", nil];
        [_documentInteractionController setURL:imageURL];
        if ([_documentInteractionController presentOpenInMenuFromRect:CGRectZero
															   inView:self.view
															 animated:YES]) {
			NSLog(@"docController opened");
		} else {
			NSLog(@"docController open error");
		}
    }
    else {
        NSLog (@"Instagram is not available");
    }
}

@end
